import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { UserLoginVO } from "@/types";

interface AuthState {
  user: UserLoginVO | null;
  permissions: string[];
  roles: string[];
  isAuthenticated: boolean;
  setUser: (user: UserLoginVO) => void;
  setPermissions: (permissions: string[]) => void;
  setRoles: (roles: string[]) => void;
  logout: () => void;
  hasPermission: (permission: string) => boolean;
  hasRole: (role: string) => boolean;
}

const useAuthStore = create<AuthState>()(
  persist<AuthState>(
    (set, get) => ({
      user: null,
      permissions: [],
      roles: [],
      isAuthenticated: false,

      setUser: (user) =>
        set({
          user,
          isAuthenticated: true,
          permissions: user.permissionList || [],
          roles: user.roleList || [],
        }),

      setPermissions: (permissions) => set({ permissions }),

      setRoles: (roles) => set({ roles }),

      logout: () =>
        set({
          user: null,
          permissions: [],
          roles: [],
          isAuthenticated: false,
        }),

      hasPermission: (permission) => {
        const { permissions } = get();
        return permissions.includes(permission);
      },

      hasRole: (role) => {
        const { roles } = get();
        return roles.includes(role);
      },
    }),
    {
      name: "auth-storage",
    },
  ),
);

export default useAuthStore;
